package com.hisense.ovcloud.acjulink.server;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.net.NetSocket;
import io.vertx.core.parsetools.RecordParser;
import io.vertx.rxjava3.FlowableHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.stream.Stream;

@Slf4j
@Component
public class TCPClient extends AbstractVerticle {
    @Override
    public void start() throws Exception {
        vertx.createNetClient().connect(1234, "localhost", res -> {

            if (res.succeeded()) {
                NetSocket socket = res.result();

                RecordParser parser = RecordParser.newDelimited("\n", socket);

                FlowableHelper.toFlowable(parser)
                        .map(buffer -> buffer.toString("UTF-8"))
                        .subscribe(greeting -> System.out.println("Net client receiving: " + greeting), t -> {
                            t.printStackTrace();
                            socket.close();
                        }, socket::close);

                // Now send some data
                Stream.of("John", "Joe", "Lisa", "Bill").forEach(name -> {
                    System.out.println("Net client sending: " + name);
                    socket.write(name);
                    socket.write("\n");
                });

            } else {
                System.out.println("Failed to connect " + res.cause());
            }
        });
    }
}
